package com.lnkwe.controller;

import com.alibaba.fastjson.JSONObject;
import com.lnkwe.config.BaseConfig;
import com.lnkwe.sys.service.SysAttService;
import com.lnkwe.sys.service.SysUEditorService;
import com.lnkwe.sys.ueditor.ConfigManager;
import com.lnkwe.sys.ueditor.define.ActionMap;
import com.lnkwe.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by lijing on 2016-06-29.
 */
@Controller
@RequestMapping("/ueditor")
public class UEditorController {
    @Autowired
    private SysAttService sysAttService;

    @Autowired
    private SysUEditorService sysUEditorService;

    @Autowired
    private BaseConfig baseConfig;

    @RequestMapping("/handler")
    @ResponseBody
    void handler(HttpServletRequest request, HttpServletResponse response) {
        JSONObject jsonObject = new JSONObject();
        PrintWriter pw = null;
        try {
            request.setCharacterEncoding("utf-8");

            response.setHeader("Content-Type", "text/html;charset=utf-8");
            pw = response.getWriter();
            String callbackName = request.getParameter("callback");
            String actionType = request.getParameter("action");
            String contextPath = request.getContextPath();
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            ConfigManager configManager = ConfigManager.getInstance(rootPath, contextPath, request.getRequestURI());

            int actionCode = ActionMap.getType(actionType);
            switch (actionCode) {

                case ActionMap.CONFIG:
                    jsonObject = configManager.getAllConfig();
                    jsonObject.put("imageUrlPrefix",this.baseConfig.getStaticServer());
                    break;
                case ActionMap.UPLOAD_IMAGE:
                case ActionMap.UPLOAD_SCRAWL:
                case ActionMap.UPLOAD_VIDEO:
                case ActionMap.UPLOAD_FILE:
                    jsonObject= FileUploadUtil.getInstance().upload(request,baseConfig);
                    break;

                case ActionMap.CATCH_IMAGE:

                    break;

                case ActionMap.LIST_IMAGE:
                case ActionMap.LIST_FILE:

                    break;

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
        pw.print(jsonObject.toString());


    }

}
